<template>
  <custom-modal-page :visible.sync="visible">
    <div class="add-material-in-bound-page">
      <div class="add-material-in-bound-container">
        <div class="zhgd-data-report-header" header="新增">
          <a-button type="primary" ghost class="back-button" @click="back()">
            返回
          </a-button>
        </div>
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" :show-arrow="false">
            <!-- 自定义头部左边 -->
            <template slot="header">
              <div @click.stop class="customize-text" header="物料信息"></div>
            </template>
            <!-- 自定义头部右边边 -->
            <template slot="extra">
              <div class="customize-extra">
                {{ activeKey.includes("1") ? "收起" : "展开" }}
                <div
                  class="icon"
                  :class="[activeKey.includes('1') && 'active']"
                >
                  <bj-icon-font type="xl" color="#0068B7" :size="10" />
                </div>
              </div>
            </template>
            <!-- 物料信息-详细内容 -->
            <div class="materialinfo-container">
              <!-- 搜索区域 -->
              <div class="screenConditions-container">
                <a-form-model
                  ref="ruleForm"
                  class="ant-advanced-search-form"
                  :model="materialInfoForm"
                  :rules="materialInfoRules"
                >
                  <a-row :gutter="24">
                    <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="5" :xxl="5">
                      <a-form-model-item label="标段：">
                        <SelectBlock
                          :allowClear="true"
                          v-model="materialInfoForm.orgCode"
                          disabled
                          show
                        ></SelectBlock>
                      </a-form-model-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="5" :xxl="5">
                      <a-form-model-item label="批次：">
                        <a-input
                          v-model="materialInfoForm.batch"
                          placeholder="请输入批次"
                          :max-length="50"
                        />
                      </a-form-model-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="5" :xxl="5">
                      <a-form-model-item label="入库时间：" prop="date">
                        <a-date-picker
                          placeholder="请选择入库时间"
                          v-model="materialInfoForm.date"
                          :format="materialInfoForm.dateFormat"
                          :valueFormat="materialInfoForm.dateFormat"
                          :show-time="{ format: materialInfoForm.dateFormat }"
                        />
                      </a-form-model-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="9" :xxl="9">
                      <a-button
                        type="primary"
                        class="choose-material-button"
                        @click="openChooseMaterial()"
                      >
                        选择物料</a-button
                      >
                    </a-col>
                  </a-row>
                </a-form-model>
              </div>
              <!-- table -->
              <div class="table-container">
                <TableView>
                  <template>
                    <a-table
                      rowKey="id"
                      :columns="tableColumns"
                      :data-source="selectListData"
                      :pagination="pager"
                    >
                      <template slot="index" slot-scope="text, record, index">
                        {{ index + 1 }}
                      </template>
                      <template slot="nums" slot-scope="text, record">
                        <a-input
                          :max-length="10"
                          placeholder="请输入数量"
                          v-model="tableInput[record.id + '']['nums']"
                        ></a-input>
                      </template>
                      <template slot="operate" slot-scope="text, record">
                        <a-button
                          type="link"
                          class="danger"
                          style="color: red"
                          @click="deleteConfirm(record)"
                          >删除</a-button
                        >
                      </template>
                      <!-- <template slot="footer">
                        总金额：{{ totalPrice.toFixed(2) }}元
                      </template> -->
                    </a-table>
                  </template>
                </TableView>
              </div>
            </div>
          </a-collapse-panel>
          <a-collapse-panel key="2" :show-arrow="false">
            <!-- 自定义头部左边 -->
            <template slot="header">
              <div @click.stop class="customize-text" header="货源信息"></div>
            </template>
            <!-- 自定义头部右边边 -->
            <template slot="extra">
              <div class="customize-extra">
                {{ activeKey.includes("2") ? "收起" : "展开" }}
                <div
                  class="icon"
                  :class="[activeKey.includes('2') && 'active']"
                >
                  <bj-icon-font type="xl" color="#0068B7" :size="10">
                  </bj-icon-font>
                </div>
              </div>
            </template>
            <div class="goods-container">
              <a-form-model
                class="ant-advanced-search-form"
                :model="goodsInfoForm"
              >
                <a-row :gutter="24">
                  <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" :xxl="12">
                    <a-form-model-item
                      label="来源/产地:"
                      class="place-origin-item"
                    >
                      <a-select
                        allowClear
                        showSearch
                        labelInValue
                        :filter-option="filterOption"
                        placeholder="请选择省"
                        v-model="goodsInfoForm.area.province"
                        @change="provinceChange"
                      >
                        <a-select-option
                          :value="item.code"
                          :label="item.name"
                          v-for="item in goodsInfoForm.provinceData"
                          :key="item.code"
                        >
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                      <a-select
                        allowClear
                        showSearch
                        labelInValue
                        :filter-option="filterOption"
                        placeholder="请选择市"
                        v-model="goodsInfoForm.area.city"
                        @change="cityChange"
                      >
                        <a-select-option
                          :value="item.code"
                          :label="item.name"
                          v-for="item in goodsInfoForm.cityData"
                          :key="item.code"
                        >
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                      <a-select
                        allowClear
                        showSearch
                        placeholder="请选择区"
                        labelInValue
                        :filter-option="filterOption"
                        v-model="goodsInfoForm.area.area"
                      >
                        <a-select-option
                          :value="item.code"
                          :label="item.name"
                          v-for="item in goodsInfoForm.areaData"
                          :key="item.code"
                        >
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                  <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="6">
                    <a-form-model-item label="试验检测编号:">
                      <a-input
                        allowClear
                        :max-length="64"
                        placeholder="请输入试验检测编号"
                        v-model="goodsInfoForm.monitorCode"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="6">
                    <a-form-model-item label="质量证明编号:">
                      <a-input
                        allowClear
                        :max-length="64"
                        placeholder="请输入质量证明编号"
                        v-model="goodsInfoForm.certificateNumber"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="6">
                    <a-form-model-item label="入库人:">
                      <a-input
                        allowClear
                        :max-length="20"
                        placeholder="请输入入库人"
                        v-model="goodsInfoForm.warehousePeople"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="6">
                    <a-form-model-item label="检查人:">
                      <a-input
                        allowClear
                        :max-length="20"
                        placeholder="请输入检查人"
                        v-model="goodsInfoForm.checkPeople"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="6">
                    <a-form-model-item label="车牌号:">
                      <a-input
                        allowClear
                        placeholder="请输入车牌号"
                        :max-length="20"
                        v-model="goodsInfoForm.licenseNumber"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="6">
                    <a-form-model-item label="使用部位:">
                      <a-input
                        allowClear
                        :max-length="100"
                        placeholder="请输入使用部位"
                        v-model="goodsInfoForm.useParts"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" :xxl="24">
                    <a-form-model-item label="备注:">
                      <a-input
                        style="width: 100%"
                        allowClear
                        placeholder="请输入备注"
                        :max-length="200"
                        type="textarea"
                        v-model="goodsInfoForm.note"
                      />
                    </a-form-model-item>
                  </a-col>
                  <!-- <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" :xxl="24">
                    <a-form-model-item label="上传图片:">
                      <bj-upload-img
                        v-model="imgList"
                        @change="selfImgUpload($event)"
                      ></bj-upload-img>
                    </a-form-model-item>
                  </a-col> -->
                  <!-- <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" :xxl="24">
                    <a-form-model-item label="上传附件:">

                      <bj-upload-file
                        v-model="defaultFileList"
                        :viewMode="false"
                        @change="selfFileUpload($event)"
                        :count="20"
                        @download="download($event)"
                        @preview="viewFile($event)"
                        :replaceFields="{
                          fileName: 'realFileName',
                          fileSize: 'fileSize',
                          fileType: 'fileType',
                          fileUrl: 'fileUrl',
                        }"
                      ></bj-upload-file>
                    </a-form-model-item>
                  </a-col> -->
                </a-row></a-form-model
              >
            </div>
          </a-collapse-panel>
        </a-collapse>
      </div>
      <div class="button-warp">
        <a-button @click="back()">取消</a-button>
        <a-button type="primary" @click="onSubmit" :loading="submitLoading">
          确定
        </a-button>
      </div>
      <!-- 选择物料弹窗 -->
      <ChooseMaterial
        :orgCode="materialInfoForm.orgCode"
        :visible.sync="chooseMaterial.visible"
        :selectListData.sync="selectListData"
        :selectedRowKeys.sync="selectedRowKeys"
      ></ChooseMaterial>
    </div>
  </custom-modal-page>
</template>

<script>
import ScreenConditions from "@/components/ScreenConditions";
import SelectBlock from "@/components/wisdom-beam/SelectBlock";
import bjRangeCalendar from "@/components/bj-range-calendar";
import ChooseMaterial from "../components/ChooseMaterial.vue";
import paginationMixins from "@/mixins/pagination";
import TableView from "@/components/tableView";
import areaData from "@/data/area-json.js";
import { getNodeByKey } from "@/utils";
import {
  uploadFileByType,
  addMaterialInbaseInfo,
} from "@/api/wisdom-beam/material-app";
import bjUploadImg from "@/components/bj-upload-img";
import bjUploadFile from "@/components/bj-upload-file";
export default {
  components: {
    ScreenConditions,
    SelectBlock,
    bjRangeCalendar,
    ChooseMaterial,
    TableView,
    bjUploadImg,
    bjUploadFile,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    orgCode: {
      type: Object,
      default: () => {
        return {};
      },
    },
    warehouseId: {
      type: String,
      default: "",
    },
  },
  mixins: [paginationMixins],
  data() {
    return {
      imgList: [],
      totalPrice: 0,
      submitLoading: false,
      selectedRowKeys: [],
      selectListData: [],
      tableColumns: [
        {
          title: "序号",
          dataIndex: "index",
          key: "index",
          width: "80px",
          scopedSlots: { customRender: "index" },
        },
        {
          title: "物料名称",
          dataIndex: "name",
          key: "name",
          width: "200px",
        },
        {
          title: "物料规格",
          dataIndex: "norms",
          key: "norms",
          width: "100px",
        },
        {
          title: "型号",
          dataIndex: "model",
          key: "model",
          width: "100px",
        },
        {
          title: "材质",
          dataIndex: "material",
          key: "material",
          width: "100px",
        },
        {
          title: "计量单位",
          dataIndex: "unit",
          key: "unit",
          width: "100px",
        },
        {
          title: "供应商",
          dataIndex: "supplier",
          key: "supplier",
          width: "200px",
        },
        {
          title: "物料类型",
          dataIndex: "materialTypeName",
          key: "materialTypeName",
          width: "100px",
        },
        {
          title: "物料大类",
          dataIndex: "typeName",
          key: "typeName",
          width: "100px",
        },
        {
          title: "数量",
          dataIndex: "nums",
          key: "nums",
          scopedSlots: { customRender: "nums" },
          width: "200px",
        },
        // {
        //   title: "单价(元)",
        //   dataIndex: "price",
        //   key: "price",
        //   width: "100px",
        // },
        // {
        //   title: "税率(%)",
        //   dataIndex: "taxRate",
        //   key: "taxRate",
        //   width: "100px",
        // },
        {
          title: "操作",
          dataIndex: "operate",
          key: "operate",
          width: "150px",
          scopedSlots: { customRender: "operate" },
        },
      ],
      tableData: [],
      //选择物料
      chooseMaterial: {
        visible: false,
      },
      tableInput: {},
      ////////////////////////////////////////
      //物料信息
      materialInfoForm: {
        //标段
        orgCode: undefined,
        //批次
        batch: undefined,
        //日期
        dateFormat: "YYYY-MM-DD HH:mm:ss",
        date: "",
      },
      materialInfoRules: {
        date: [
          { required: true, message: "请选择入库时间", trigger: "change" },
        ],
      },
      //货源信息
      goodsInfoForm: {
        //省数据
        provinceData: areaData,
        //市数据
        cityData: [],
        //区数据
        areaData: [],
        area: {
          //省
          province: undefined,
          //市
          city: undefined,
          //区
          area: undefined,
        },
        //监测编码
        monitorCode: "",
        //质量证明编号
        certificateNumber: "",
        //备注
        note: "",
        //入库人
        warehousePeople: "",
        //检查人
        checkPeople: "",
        //车牌号
        licenseNumber: "",
        //使用部位
        useParts: "",
        //上传图片
        uploadImgList: [],
        //上传附件
        uploadFileList: [],
      },
      defaultFileList: [],
      //////////////////////////////////////////
      conditions: {
        //标段
        orgCode: undefined,
        //显示货物
        inventoryType: {
          replaceFields: { key: "key", label: "value" },
          data: [
            { key: "1", value: "无库存" },
            { key: "2", value: "有库存" },
          ],
          value: undefined,
        },
        //供应商
        supplier: "",
        //日期
        dateFormat: "YYYY-MM-DD HH:mm:ss",
        dateRange: [],
      },
      activeKey: ["1", "2"],
      options: [],
    };
  },
  watch: {
    tableInput: {
      handler(val) {
        this.totalPrice = 0;
        Object.keys(val).forEach((key) => {
          this.totalPrice +=
            parseFloat(val[key].price) *
            parseFloat(val[key].nums == "" ? 0 : val[key].nums);
        });
      },
      deep: true,
    },

    //监听物料选择
    selectListData: {
      handler(data) {
        data.forEach((item) => {
          this.$set(this.tableInput, item.id + "", {
            nums: this.tableInput[item.id + ""]
              ? this.tableInput[item.id + ""].nums
              : "",
            price: item.price,
          });
        });
      },
      immediate: true,
    },

    visible: {
      handler(val) {
        if (val) {
          this.materialInfoForm.orgCode = this.orgCode;
        }
      },
      immediate: true,
    },
  },
  methods: {
    //返回
    back() {
      this.$emit("update:visible", false);
    },
    //确定
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.submitAdd();
        } else {
          return false;
        }
      });
    },

    //删除
    deleteConfirm(record) {
      let { id } = record;
      this.selectListData = this.selectListData.filter((v) => v.id != id);
      this.selectedRowKeys = this.selectedRowKeys.filter((v) => v != id);
      this.$delete(this.tableInput, id + "");
    },

    //自定义图片上传事件
    selfImgUpload({ file }) {
      let formData = new FormData();
      formData.append("uploadFile", file);
      uploadFileByType(formData, "MATERIALINBASE_IMAGE")
        .then((res) => {
          let { data } = res;
          this.goodsInfoForm.uploadImgList.push({
            fileId: data.result.fileId,
            uid: file.uid,
          });
        })
        .catch((_) => {});
    },

    //删除已上传的图片
    removeImgFile(file) {
      let { uid } = file;
      this.goodsInfoForm.uploadImgList =
        this.goodsInfoForm.uploadImgList.filter((v) => v.uid != uid);
    },

    //自定义附件上传事件
    selfFileUpload({ file }) {
      let formData = new FormData();
      formData.append("uploadFile", file);
      uploadFileByType(formData, "MATERIALINBASE_FILE")
        .then((res) => {
          let { data } = res;
          this.goodsInfoForm.uploadFileList.push({
            fileId: data.result.fileId,
            uid: file.uid,
          });
        })
        .catch((_) => {});
    },

    //删除已上传的附件
    removeFile(file) {
      let { uid } = file;
      this.goodsInfoForm.uploadFileList =
        this.goodsInfoForm.uploadFileList.filter((v) => v.uid != uid);
    },

    //新增
    submitAdd() {
      let { orgCode, date, batch } = this.materialInfoForm;

      let {
        area: { province, city, area },
        monitorCode,
        certificateNumber,
        note,
        warehousePeople,
        checkPeople,
        licenseNumber,
        useParts,
        uploadImgList,
        uploadFileList,
      } = this.goodsInfoForm;

      let materialBasicParams = [];
      Object.keys(this.tableInput).forEach((key) => {
        materialBasicParams.push({
          baseId: key,
          total: this.tableInput[key]["nums"],
        });
      });
      let requestData = {
        //标段
        orgCode: orgCode?.key || "",
        //批次
        batch: batch || "",
        //入库时间
        inbaseTime: date || "",
        //产地来源
        sourceAddr:
          (province?.label || "") + (city?.label || "") + (area?.label || ""),
        //监测编号
        testSerialNumber: monitorCode || "",
        //证明编号
        qualitySerialNumber: certificateNumber || "",
        //备注
        remark: note || "",
        //入库人
        inbaseUser: warehousePeople || "",
        //检查人
        checkUser: checkPeople || "",
        //车牌号
        carNumber: licenseNumber || "",
        //使用部位
        position: useParts || "",
        //上传图片
        pic: uploadImgList.map((v) => v.fileId).toString(),
        //上传附件
        enclosure: uploadFileList.map((v) => v.fileId).toString(),
        //数量数组
        materialBasicParams,
        //仓库名称
        warehouseId: this.warehouseId,
      };
      this.submitLoading = true;
      addMaterialInbaseInfo(requestData)
        .then((res) => {
          this.$message.success("操作成功！");
          this.back();
          let { dicValue } = this.$parent.selectTreeNode;
          this.$parent.getListData(dicValue);
        })
        .catch((_) => {})
        .finally((_) => {
          this.submitLoading = false;
        });
    },

    //监听省份选择
    provinceChange(value) {
      if (value) {
        let { key } = value;
        let currentProvince = getNodeByKey(key, "code", areaData, "children");
        this.goodsInfoForm.cityData = currentProvince.children || [];
        this.goodsInfoForm.areaData = [];
      } else {
        this.goodsInfoForm.cityData = [];
        this.goodsInfoForm.areaData = [];
        this.goodsInfoForm.area.city = undefined;
        this.goodsInfoForm.area.area = undefined;
      }
    },

    //监听市选择
    cityChange(value) {
      if (value) {
        let { key } = value;
        let currentCity = getNodeByKey(key, "code", areaData, "children");
        this.goodsInfoForm.areaData = currentCity.children || [];
      } else {
        this.goodsInfoForm.areaData = [];
        this.goodsInfoForm.area.area = undefined;
      }
    },

    //打开选择物料弹窗
    openChooseMaterial() {
      this.chooseMaterial.visible = true;
      this.selectedRowKeys = this.selectListData.map((v) => v.id);
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
.add-material-in-bound-page {
  box-sizing: border-box;
  height: 100%;
  padding: 0 0 0 0;
  background: #fff;
  margin-left: 10px;
  .flex();
  flex-direction: column;
  //
  overflow: hidden;
  textarea {
    height: 70px;
  }
  .materialinfo-container {
    .screenConditions-container {
      padding: 0 5px 0 30px;
    }
    .choose-material-button {
      float: right;
      margin-top: 2px;
    }
    /deep/.ant-form-item {
      .flex();
      .ant-form-item-label {
        width: 80px !important;
        flex-shrink: 0;
        label {
          color: #999;
        }
      }
      .ant-form-item-control-wrapper {
        flex: 1;
        .ant-form-item-children {
          display: block;
          width: 100%;
          .ant-calendar-picker {
            width: 100%;
          }
        }
      }
    }
    .table-container {
      /deep/.ant-table {
        border-top: none;
        .ant-table-body {
          border-top: 1px solid #e8e8e8;
          overflow: auto !important;
        }
        .ant-table-placeholder {
          border-top: 1px solid #e8e8e8 !important;
        }
        .ant-table-footer {
          color: var(--echart-blue);
          font-size: 16px;
          padding-left: 50px;
          border-bottom: 1px solid #e8e8e8;
        }
      }
    }
  }
  .goods-container {
    padding: 0 100px 0 0;
    /deep/.upload-file-container {
      .ant-upload-list {
        width: 476px;
        height: 136px;
        background: #ffffff;
        border: 1px solid #dcdee2;
        border-radius: 4px;
        padding: 6px 8px;
        .custom-scrollbar();
      }
    }

    /deep/.ant-form-item {
      .flex();
      &.place-origin-item {
        .ant-form-item-control {
          .ant-form-item-children {
            width: 100%;
            .flex();
          }

          .ant-select {
            flex: 1;
            margin-right: 10px;
            margin-top: 4px;
            &:last-child {
              margin-right: 0;
            }
          }
        }
      }
      .ant-form-item-label {
        width: 140px;
        label {
          color: #999;
        }
      }
      .ant-form-item-control-wrapper {
        flex: 1;
      }
    }
  }
  .add-material-in-bound-container {
    flex: 1;
    .custom-scrollbar();
    //折叠面板
    /deep/.ant-collapse {
      background-color: #ffffff;
      border: 0;
      border-radius: 0;
      border-top: 2px solid #f3f4f6;
      .ant-collapse-content {
        border-top: 0;
        border-radius: 0;
        background-color: #ffffff;
      }
      .ant-collapse-header {
        border-radius: 0;
      }
      .ant-collapse-item {
        border: 0;
        border-bottom: none;
      }
      .ant-collapse-item:last-child {
        border-radius: 0 !important;
      }
      .ant-collapse-content-box {
        padding: 0;
        .base-content {
          padding: 0 130px 20px 0;
        }
        .contract-content {
          padding-bottom: 55px;
          .ant-table-fixed {
            border: 1px solid #dcdee2;
            border-bottom: 0;
          }
        }
      }
    }
  }
  .button-warp {
    height: 60px;
    background: #fff;
    .flex();
    justify-content: center;
    align-items: center;
    border-top: 1px solid #e8e8e8;
  }
}
</style>
